package com.fair.concurrency;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 探讨下生产者与消费者的问题
 *
 * @Author: 朝花不迟暮
 * @Description:
 * @Date: 2022/11/17
 */
public class PcTest implements Runnable {

    public static Queue<String> queue = new LinkedBlockingQueue<>();

    public static final Object obj = new Object();

    @Override
    public void run() {
        while (true) {
            if (!queue.isEmpty()) {
                String str = queue.poll();
                if (StrUtil.isNotBlank(str)) {
                    System.out.println("消费者: " + Thread.currentThread().getName() + "消费数据: " + str);
                }
            } else {
                synchronized (obj) {
                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        // 启动消费者
        for (int i = 0; i < 10; i++) {
            ThreadUtil.execute(new PcTest());
        }
        // 生产数据
        for (int i = 0; i < 1000; i++) {
            new PcTest().put("i: " + i);
        }
    }

    public void put(String s) {
        queue.add(s);
        synchronized (obj) {
            obj.notifyAll();
        }
    }
}
